<template>
	<view>

		<view class="navigation" style="height: 44px;background-color: #fff;"></view>

		<!-- 导航栏 -->
		<view class="content">
		    <!-- 距离顶部的距离 刚好留出状态栏即可 即statusBarHeight -->
		    <view class="topNav" :style="{height:navHeight+'px',paddingTop:statusBarHeight+'px'}">
				<view class="nav-left" @tap="goToBack">
					<up-icon name="arrow-left"  size="22"></up-icon>
				</view>
				<view class=" nav-center">
					我的线索
				</view>
				<view class="nav-right">
					
				</view>
		    </view>
		</view>
	
		<!-- 标签页 -->
		<view class="tabs">
			<up-tabs :list="list1" lineWidth="100" lineColor="#4095E5" :activeStyle="{ color: '#4095E5', fontWeight: 'bold', 
			transform: 'scale(1.05)' }" :inactiveStyle="{ color: '#606266', transform: 'scale(1)' }" 
			itemStyle="height: 34px;width:50%"  @change="changeTabs">
			</up-tabs>
			<view style="border-top:1px solid #ccc;margin-top: -6rpx;">
				
			</view>
		</view>
		
		<!-- 查询 -->
		<view class="search">
			<view class="input">
				<up-search placeholder="搜索线索姓名/手机号" v-model="searchFor" shape="share" :showAction="false"
					class="seach_input" @change="startSearch()"></up-search>
			</view>
			<view class="arcoDesign" @tap="optionClue">
				<image src="/static/imgs/clueManage/arcoDesign-filter.png" mode="" style="width: 36rpx;height: 36rpx;opacity: .4;"></image>
				<text style="margin-left: 10rpx;margin-right: 10rpx;" >筛选</text>
			</view>
		</view>
		
		<!-- 内容 -->
		<view class="tabsData">
			<scroll-view :scroll-top="0" scroll-y="true" class="scroll-Y" v-if="tableData.length != 0">
				<!-- <up-card :show-head='false' v-for="item in tableData" :key="item.customerId" style="margin:10rpx 30rpx;" @click="goToPages(item)" :style="{'backgroundColor':isTransRowStyle(item.isTrans)}">
					<template #body> -->
					    <view class="cardBody" v-for="item in tableData" :key="item.customerId" @click="goToPages(item)" :style="{'backgroundColor':isTransRowStyle(item.isTrans)}">
							<view class="cardBodyTop">
								<view class="cardBodyTopLeft">
									<view class="infoName">
										{{item.name}}
									</view>
									<view class="infoGrade">
										<up-tag text="A" plain size="mini" type="error" v-if="item.ranks=='A'"></up-tag>
										<up-tag text="B" plain size="mini" plainFill v-if="item.ranks=='B'"></up-tag>
										<up-tag text="C" plain size="mini" type="warning"v-if="item.ranks=='C'"></up-tag>
										<up-tag text="D" plain size="mini" type="info" v-if="item.ranks=='D'"></up-tag>
									</view>
									<view class="infoSource">
										<up-tag :text="item.source" plain size="mini" type="success" plainFill></up-tag>
									</view>
								</view>
								<view class="cardBodyTopRight">
									{{item.progressName}}
								</view>
							</view>
							<view class="cardBodyCenter">
								<view style="display: inline-block;width: 55%;">
									联系方式1：{{item.phoneFirst}}
								</view>
								<view style="display: inline-block;width: 45%;text-align: right;" v-if="item.followName !== ''">
									跟进人：{{item.followName}}
								</view>
							</view>
							<view class="bottom">
								<view class="cardBodyBottom">
									<view class="classTime">
										届次：{{item.classTime}}
									</view>
									<view class="college">
										院校：{{item.college}}
									</view>
								</view>
							</view>
							
							<view class="bottomTime">
								<view style="width: 70%;color: rgba(154,154,154,1);font-size: 28rpx;">
									最近操作时间：{{item.nearestTime}}
								</view>
								<view class="operate">
									<image src="/static/imgs/myClue/details.png" mode="" class="operateImg" @click.stop="goToPages(item)"></image>
									<image src="/static/imgs/myClue/toCustomer.png" mode="" class="operateImg" @click.stop="toClient(item.progressName,item.customerId)"></image>
									<image src="/static/imgs/myClue/delete.png" mode=""class="operateImg" @click.stop="toSea(item.customerId)"></image>
								</view>
							</view>
							
							
							
							<view class="prompt" v-if="showTabs == '待沟通线索' && item.remarks !== null ">
								{{item.remarks}}
							</view>
							
						</view>
					<!-- </template>
				</up-card> -->
				
			</scroll-view>
			
			<view v-else>
				<view class="noData">
					<image src="/static/imgs/myClue/noData.png" mode="" style="max-height: 100%;max-width: 100%;"></image>
				</view>
			</view>
			
			<u-pagination v-show="isShowPages" :current-page="currentPage" :page-size="pageSize" :total="total" :hideOnSinglePage="true" layout="prev, pager, next"  @current-change="handleCurrentChange" style="margin:10rpx 30rpx;" />
			
		</view>
	
		<!-- 筛选 -->
		<up-popup v-model:show="showOptions" mode="right" :customStyle="{'width':'650rpx','padding-top':'44px'}">
			<view>
				<view class="progress">
					<view style="font-size: 30rpx;">流程进展</view>
					<view >
						<view v-for="item in progressArray" :key="item.progressId" style="display: inline-block;width: 30%;margin:10rpx 0 0 10rpx;border: 1px solid #ccc;">
							<up-button :text="item.progressName" :type="includeProgress(item.progressId)" @tap="selectProgress(item.progressId)"></up-button>
						</view>
					</view>
				</view>
				<up-divider></up-divider>
				<view class="progress">
					<view style="font-size: 30rpx;">客户来源</view>
					<view>
						<view v-for="item in actionsSource" :key="item.name" style="display: inline-block;width: 30%;margin:10rpx 0 0 10rpx;border: 1px solid #ccc;">
							<up-button :text="item.name" :type="includeSource(item.name)" @tap="selectSource(item.name)"></up-button>
						</view>
					</view>
				</view>
				<up-divider></up-divider>
				<view class="progress">
					<view style="font-size: 30rpx;">客户等级</view>
					<view style="margin-top: 10rpx;">
						<view class="gradeItem">
							<up-button text="A" :type="includeGrade('A')" @tap="selectGrade('A')"></up-button>
						</view>
						<view class="gradeItem">
							<up-button text="B" :type="includeGrade('B')" @tap="selectGrade('B')"></up-button>
						</view>
						<view class="gradeItem">
							<up-button text="C" :type="includeGrade('C')" @tap="selectGrade('C')"></up-button>
						</view>
						<view class="gradeItem">
							<up-button text="D" :type="includeGrade('D')" @tap="selectGrade('D')"></up-button>
						</view>
					</view>
				</view>
				<up-divider></up-divider>
				<view class="progress">
					<view style="font-size: 30rpx;">学校</view>
					<view style="margin-top: 10rpx;">
						 <up-input placeholder="请输入学校名称" v-model="schoolName"  border="surround" style="margin-right: 24rpx;"></up-input>
					</view>
				</view>
				<up-divider></up-divider>
				<view class="progress" style="display: flex;align-items: center;justify-content: space-between;margin-right: 30rpx;">
					<view style="font-size: 30rpx;">届次</view>
					<view  @tap="showClassTime = true">
						 <text :style="{'color': classTimes == '请选择'? ' rgba(190,190,190,1)': ''}" >{{classTimes}}</text>
						 <text style="margin-left: 20rpx;color:rgba(190,190,190,1)">></text>
					</view>
				</view>
				<up-divider></up-divider>
				<view class="progress" style="display: flex;align-items: center;justify-content: space-between;margin-right: 30rpx;" v-if="!(roleAuthority =='StoreStaff' )">
					<view style="font-size: 30rpx;">跟进人</view>
					<view @tap="showStaff = true">
						 <text :style="{'color': staff == '请选择'? ' rgba(190,190,190,1)': ''}" >{{staff}}</text>
						 <text style="margin-left: 20rpx;color:rgba(190,190,190,1)">></text>
					</view>
				</view>
				<up-divider v-if="!(roleAuthority =='StoreStaff' )"></up-divider>
			</view>
			<view style="display: flex;align-items: center;position: absolute;bottom: 10rpx;width: 100%;">
				<up-button text="重置" style="width: 50%;" @tap="resetOptions"></up-button>
				<up-button text="确认" color="linear-gradient(to right, rgb(147,210,243), rgb(64,149,229))" style="width: 50%;" @tap="submitOptions"></up-button>
			</view>
		</up-popup>
		
		<!-- 届次选择 -->
		<up-action-sheet :show="showClassTime" :actions="actionsClassTime" title="请选择届次" 
			@close="showClassTime = false" @select="classTimeSelect" wrapMaxHeight="600rpx" >
		</up-action-sheet>
		
		<!-- 跟进人选择 -->
		<up-action-sheet :show="showStaff" :actions="actionsStaff" title="请选择跟进人" 
			@close="showStaff = false" @select="staffSelect" wrapMaxHeight="600rpx" >
		</up-action-sheet>
		
	</view>
</template>

<script setup>
	import { ref,reactive, onMounted } from 'vue';
	import { onShow } from '@dcloudio/uni-app';
	import { cemCustomerInfoGetProgress,userFindBusinessUser,cemCustomerInfoFindTodayComList,cemCustomerInfoFindMyCustomerList } from '../../utils/clue';
	import { cemCustomerInfoToClient,cemCustomerInfoToSea  } from '../../utils/myClue';
	let navHeight = ref('');// 导航栏高度
	let statusBarHeight = ref('');// 状态栏高度
	
	// ============== 查询 ==============//
	// 要查询的内容
	let searchFor = ref('')
	// 客户姓名
	let customerName = ref('')
	// 客户手机号
	let customerPhone = ref('')
	
	let startSearch = ()=>{
		// 正则表达式判断汉字
		const isChinese = /^[\u4e00-\u9fa5]+$/.test(searchFor.value);
		// 正则表达式判断数字
		const isNumber = /^\d+$/.test(searchFor.value); 
		
		if(searchFor.value == ''){
			customerName.value= '';
			customerPhone.value = '';
			pageChange(1); 
		}else{
			if (isChinese) {
				customerName.value = searchFor.value;
				pageChange(1); 
			} else if (isNumber) {
				customerPhone.value = searchFor.value
				if(customerPhone.value.length == 11){
					pageChange(1); 
				}
			} else {
				uni.showToast({
					title: '请正确输入内容',
					icon: 'error',
					duration: 2000
				})
				searchFor.value = ''
				pageChange(1); 
			}
		}
	}
	
	// 返回
	let goToBack = ()=>{
		uni.switchTab({
			url:'/pages/workbenches/workbenches'
		})
	}
	
	// ============== 标签页 ==============//
	// 显示的是哪个标签
	const showTabs = ref('全部线索')
	
	const list1 = reactive([  
	    { name: '全部线索' },  
	    { name: '待沟通线索' }
	]);  
	
	// 切换标签页
	let changeTabs = (tabItem )=>{
		isShowPages.value = false
		searchFor.value = ''
		customerName.value = ''
		customerPhone.value = ''
		progressOptions.value.length = 0
		sourceOptions.value.length = 0
		gradeOptions.value.length = 0
		schoolName.value = ''
		classTimes.value = '请选择'
		staff.value = '请选择'
		if(tabItem.name == '全部线索'){
			showTabs.value = '全部线索'
			
		}else if(tabItem.name == '待沟通线索'){
			showTabs.value = '待沟通线索'
		}
		pageChange(1); 
	}
	
	// ============== 流程进展字典 ==============//
	let progressArray = ref([])
	// 获取流程进展字典
	let getProgress = ()=>{
		cemCustomerInfoGetProgress().then(res=>{
			if(res.code == 200){
				progressArray.value = [];
				progressArray.value = res.data
				uni.setStorageSync('progressArray',res.data)
			}
		})
	}
	
	
	// ============== 获取线索数据 ==============//
	//表格的数据
	const tableData = ref([])
	  
	// 分页
	let isShowPages = ref(false)
	let currentPage = ref(1)
	let pageSize = ref(15)
	let total = ref(0)
	
	let handleCurrentChange = (val)=>{
		pageChange(val)
	}
	
	let pageChange = (val) =>{
		tableData.value.length = 0;
		currentPage.value = val
		const params = {
			businessId:uni.getStorageSync('businessId'),
			isClient: 1,
			pageNumber: currentPage.value,
			pageSize: pageSize.value,
			name: customerName.value,
			phoneFirst: customerPhone.value,
			college:schoolName.value,
			classTime:classTimes.value == '请选择'?null:classTimes.value,
			followId:staff.value== '请选择'?null:staffArray.value.filter(item=>item.name == staff.value)[0].userId,
			progressIds:progressOptions.value.length == 0?null:progressOptions.value.join(','),
			sources:sourceOptions.value.length == 0?null:sourceOptions.value.join(','),
			rankTwo:gradeOptions.value.length == 0?null:gradeOptions.value.join(','),
		}
			
		if (progressOptions.value.length == 0) {
			delete params.progressIds;
		}
		if (sourceOptions.value.length == 0) {
			delete params.sources;
		}
		if (gradeOptions.value.length == 0) {
			delete params.rankTwo;
		}
			
		uni.showLoading({
			title:'正在加载',
			mask:true
		})
		if(showTabs.value == '全部线索'){
			cemCustomerInfoFindMyCustomerList(params).then(res=>{
				if(res.code == 200){
					if(res.data.vos.records.length == 0){
						isShowPages.value = false
						uni.showToast({
							title: '暂无数据',
							icon: 'error',
							duration: 2000
						})
					}else{
						isShowPages.value = true
					}
					tableData.value = res.data.vos.records;
					total.value = res.data.vos.total
					tableData.value.forEach(item=>{
						item.nearestTime = item.nearestTime.split(':')[0]+':' + item.nearestTime.split(':')[1]
					});
					uni.hideLoading()
				}
			})
		}else if(showTabs.value == '待沟通线索'){
			cemCustomerInfoFindTodayComList(params).then(res=>{
				if(res.code == 200){
					if(res.data.vos.records.length == 0){
						isShowPages.value = false
						uni.showToast({
							title: '暂无数据',
							icon: 'error',
							duration: 2000
						})
					}else{
						isShowPages.value = true
					}
					tableData.value = res.data.vos.records;
					total.value = res.data.vos.total
					tableData.value.forEach(item=>{
						item.nearestTime = item.nearestTime.split(':')[0]+':' + item.nearestTime.split(':')[1]
					});
					uni.hideLoading()
				}
			})
		}
	}
	
	let roleAuthority = ref('')
	roleAuthority.value = uni.getStorageSync('roleAuthority')
	
	onShow(()=>{
		getProgress()
		getStaffArray()
		pageChange(1)
	})
	
	onMounted(()=>{
		let {
		        statusBarHeights,
		        system// 机型
		      } = uni.getSystemInfoSync()
		      // 注意返回的单位是px 不是rpx
		      // 而导航栏的高度则 = 状态栏的高度 + 判断机型的值（是ios就+40，否则+44）
		      // 这个高度刚好和胶囊对齐
			  statusBarHeight.value = statusBarHeights
		      navHeight.value = statusBarHeights + (system.indexOf('iOS') > -1 ? 40 : 44)
	})
	
	
	//===========获取本店的员工字典=============//
	let staffArray = ref([])
	
	let getStaffArray = ()=>{
		userFindBusinessUser({
			  businessId: uni.getStorageSync('businessId')
		}).then((res) => {
			actionsStaff.value = []
			staffArray.value = [];
			staffArray.value = res.data;
			for(let i=0;i<res.data.length;i++){
				actionsStaff.value.push({
					name:res.data[i].name
				})
			}
		})
	}
	
	// 筛选
	const showOptions = ref(false)
	
	// 流程进展选项
	let progressOptions = ref([])
	
	let includeProgress = (val)=>{
		if(progressOptions.value.indexOf(val) < 0 ){
			return ''
		}else{
			return 'primary'
		}
	}
	
	let selectProgress = (val) => {
		if(progressOptions.value.indexOf(val) < 0 ){
			progressOptions.value.push(val)
		}else{
			progressOptions.value.splice(progressOptions.value.indexOf(val),1)
		}
	}
	
	// 客户来源选项
	let sourceOptions = ref([])
	
	let includeSource = (val)=>{
		if(sourceOptions.value.indexOf(val) < 0 ){
			return ''
		}else{
			return 'primary'
		}
	}
	
	let selectSource = (val) => {
		if(sourceOptions.value.indexOf(val) < 0 ){
			sourceOptions.value.push(val)
		}else{
			sourceOptions.value.splice(sourceOptions.value.indexOf(val),1)
		}
	}
	
	// 客户等级选项
	let gradeOptions = ref([])
	
	let includeGrade = (val)=>{
		if(gradeOptions.value.indexOf(val) < 0 ){
			return ''
		}else{
			return 'primary'
		}
	}
	
	let selectGrade = (val) => {
		if(gradeOptions.value.indexOf(val) < 0 ){
			gradeOptions.value.push(val)
		}else{
			gradeOptions.value.splice(gradeOptions.value.indexOf(val),1)
		}
	}
	
	
	let optionClue = ()=>{
		showOptions.value = true
	}
	
	
	
	// 客户来源
	const actionsSource = ref([  
		{ name: '资源置换' },
		{ name: '老客户转介绍' },
		{ name: '机构推荐' },
		{ name: '自然流量' },
		{ name: '直播获客' },
		{ name: '流量中心获客' },
		{ name: '共享合伙人' },
	])
	
	// 学校名称
	const schoolName = ref('')
	
	// 届次选择
	let classTimes = ref('请选择')
	
	const actionsClassTime = ref([  
		{ name: '2029' },
		{ name: '2028' },
		{ name: '2027' },
		{ name: '2026' },
		{ name: '2025' },
		{ name: '2024' },
		{ name: '2023' },
		{ name: '2022' },
		{ name: '2021' },
	])
	
	let showClassTime = ref(false)
	
	let classTimeSelect =(e)=> {
		classTimes.value = e.name
	}
	
	// 跟进人筛选
	let staff = ref('请选择')
	
	const actionsStaff = ref([])
	
	let showStaff = ref(false)
	
	let staffSelect =(e)=> {
		staff.value = e.name
	}
	
	// 确认筛选
	let submitOptions = ()=>{
		uni.showToast({
			title: '筛选成功',
			icon: 'success',
			duration: 1000
		})
		showOptions.value = false
		setTimeout(function(){
			pageChange(1)
		},1000)
	}
	
	// 重置筛选
	let resetOptions= ()=>{
		console.log('重置');
		progressOptions.value.length = 0
		sourceOptions.value.length = 0
		gradeOptions.value.length = 0
		schoolName.value = ''
		classTimes.value = '请选择'
		staff.value = '请选择'
	}
	
	  //是否即将转入公海 变背景色
	  let isTransRowStyle =(val)=>{
	    if (val){
	      return 'rgb(253, 225.6, 225.6)'
	    }
	  }
	
	// 跳转页面
	let goToPages = (val)=>{
		uni.setStorageSync('clueDetails',val)
		uni.navigateTo({
			url:'/pages/clueDetails/clueDetails'
		})
	}
	
	// 转成客户
	let toClient = (val1,val2)=>{
		if(val1 == '未沟通'){
			uni.showToast({
				title: '暂无沟通记录/流程进展，请完善后再操作',
				icon: 'none',
				duration: 2000,
			})
			
		}else{
			uni.showModal({
				title: '转成客户',
				content: '您确定将此线索转成客户吗？',
				success: function (res) {
					if (res.confirm) {
						cemCustomerInfoToClient({
							customerId:val2
						}).then(res=>{
							if(res.code == 200){
								uni.showToast({
									title: res.message,
									icon: 'success',
									duration: 2000
								})
								setTimeout(()=>{
									pageChange(1)
								},2000)
							}
						})
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		}
	}
	
	// 放入公海
	let toSea = (val)=>{
		uni.showModal({
			title: '放入公海',
			content: '您确定将此线索放入公海吗？',
			success: function (res) {
				if (res.confirm) {
					console.log('用户点击确定');
					cemCustomerInfoToSea({
						customerId:val
					}).then(res=>{
						if(res.code == 200){
							uni.showToast({
								title: res.message,
								icon: 'success',
								duration: 2000
							})
							setTimeout(()=>{
								pageChange(1)
							},2000)
						}
					})
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}
	
	
</script>

<style lang="scss" scoped>
	
	/* =========导航栏========= */
	.topNav {
		width: 100%;
		height: 100rpx;
		display: flex;
		justify-content: flex-start;
		align-items: center;
		padding: 0 20rpx;
		box-sizing: border-box;
	}
	
	.nav-left {
		width: 20%;
		font-size: 36rpx;
		font-weight: 600;
	}
	
	.nav-center{
		width: 60%;
		height: 62rpx;
		padding-left: 25rpx;
		box-sizing: border-box;
		text-align: center;
		font-size: 40rpx;
	}
	 
	.nav-right {
		width: 20%;
		font-size: 36rpx;
		font-weight: 600;
		display: flex;
		justify-content: end;
	}
	 
	/* =========搜索、筛选========= */
	.search{
		display: flex;
		justify-content: space-around;
		align-items: center;
		// margin-top: 10rpx;
		padding-top: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 1px solid #efefef;
	}
	
	.input{
		width: 65%;
	}
	
	.arcoDesign{
		display: flex;
		justify-content: space-between;
		align-items: center;
		color: #9A9A9A;
	}
	
	/* =========内容========= */
	.tabsData{
		margin-top: 6rpx;
	}
	
	.cardBody{
		flex: 1;
		padding: 20rpx;
		border-bottom: 1px solid #efefef;
	}
	
	.cardBodyTop{
		display: flex;
		align-items: center;
	}
	
	.cardBodyTopLeft{
		width: 80%;
		display: flex;
		justify-content: start;
		align-items: center;
	}
	
	.infoGrade,.infoSource{
		margin-left: 20rpx;
	}
	
	.infoName{
		color: rgb(16,16,16);
		font-size: 28rpx;
		font-family: PingFangSC-regular;
	}
	
	.cardBodyTopRight{
		width: 20%;
		color: rgba(255,115,115,1);
		font-size: 28rpx;
		text-align: right;
	}
	
	.cardBodyCenter{
		margin-top: 12rpx;
		height: 40rpx;
		line-height: 40rpx;
		color: rgba(154,154,154,1);
		font-family: PingFangSC-regular;
		font-size: 28rpx;
	}
	
	.bottom{
		height: 50rpx;
		line-height: 50rpx;
	}
	
	.cardBodyBottom{
		margin-top: 12rpx;
		height: 36rpx;
		line-height: 36rpx;
		color: rgba(154,154,154,1);
		display:flex;
		justify-content: space-between;
		align-items: center;
		font-size: 28rpx;
	}
	
	.classTime{
		width: 23%;
	}
	
	.college{
		width: 75%;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	
	.bottomTime{
		height: 50rpx;
		line-height: 50rpx;
		display: flex;
		align-items: center;
	}
	
	.operate{
		width:27%;
		margin-left: 3%;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.operateImg{
		width: 50rpx;
		height: 50rpx;
	}
	
	.prompt{
		width: 100%;
		line-height: 36rpx;
		color: rgb(154,154,154);
		margin-top: 20rpx;
	}
	
	.noData{
		width: 444rpx;
		height: 444rpx;
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%,-50%);
	}
	
	.progress{
		text-align: left;
		margin:24rpx 0 12rpx 24rpx;
	}
	
	.gradeItem{
		display: inline-block;
		width: 22%;
		margin-left: 10rpx;
		border: 1px solid #ccc;
	}
	
	/* 滚动 */
	.scroll-Y {
		// height: 1320rpx;
		height: calc(100vh - 450rpx);
	}
</style>
